#
import os
import sys
import shutil
from PySide6.QtWidgets import (
    QApplication,
    QWidget,
    QFileDialog,
    QMessageBox,
    QLabel,
    QPushButton,
    QLineEdit,
    QHBoxLayout,
    QVBoxLayout,
    QListWidget,
    QListWidgetItem,
    QTextBrowser,
)
from PySide6.QtCore import Qt, QDir, QUrl, QSettings
from PySide6.QtGui import QDesktopServices
from keil_uvprojx_to_cmake import KeilProjectToCMake


class Widget(QWidget):
    def __init__(self):
        super().__init__()

        self.uvproj_filepath = ""
        self.output_directory = ""

        self.setup_ui()
        self.setWindowTitle("Keil UVPROJX to CMake Converter")
        self.resize(800, 600)

        self.uvproj_filepath = ""
        self.output_directory = ""

        self.load_config()

    def closeEvent(self, event):
        """窗口关闭事件"""
        self.save_config()
        event.accept()

    def setup_ui(self):
        #
        label1 = QLabel("uvprojx 路径:")
        label2 = QLabel("输出目录:")
        label3 = QLabel("原始信息:")
        label4 = QLabel("转换日志:")
        self.lineeditUvProjFilepath = QLineEdit()
        self.lineeditOutputDirectory = QLineEdit()
        self.pushbuttonBrowseUvProj = QPushButton("浏览")
        self.pushbuttonBrowseOutput = QPushButton("浏览")
        self.pushbuttonConvert = QPushButton("转换")
        self.listWidgetOriginalInfo = QListWidget()
        self.textBrowserLog = QTextBrowser()

        layout1 = QHBoxLayout()
        layout1.addWidget(label1)
        layout1.addWidget(self.lineeditUvProjFilepath)
        layout1.addWidget(self.pushbuttonBrowseUvProj)

        layout2 = QHBoxLayout()
        layout2.addWidget(label2)
        layout2.addWidget(self.lineeditOutputDirectory)
        layout2.addWidget(self.pushbuttonBrowseOutput)

        layout3 = QHBoxLayout()
        layout3.addStretch(1)
        layout3.addWidget(self.pushbuttonConvert)

        layout4_1 = QVBoxLayout()
        layout4_1.addWidget(label3)
        layout4_1.addWidget(self.listWidgetOriginalInfo)

        layout4_2 = QVBoxLayout()
        layout4_2.addWidget(label4)
        layout4_2.addWidget(self.textBrowserLog)

        layout4 = QHBoxLayout()
        layout4.addLayout(layout4_1)
        layout4.addLayout(layout4_2)

        layout = QVBoxLayout()
        layout.addLayout(layout1)
        layout.addLayout(layout2)
        layout.addLayout(layout3)
        layout.addLayout(layout4)

        self.setLayout(layout)

        self.pushbuttonBrowseUvProj.clicked.connect(
            self.on_pushbuttonBrowseUvProj_clicked
        )
        self.pushbuttonBrowseOutput.clicked.connect(
            self.on_pushbuttonBrowseOutput_clicked
        )
        self.pushbuttonConvert.clicked.connect(self.on_pushbuttonConvert_clicked)

    def load_config(self):
        """加载配置"""
        settings = QSettings("config.ini", QSettings.Format.IniFormat)

        self.uvproj_filepath = str(settings.value("uvproj_filepath", ""))
        self.output_directory = str(settings.value("output_directory", ""))

        self.lineeditUvProjFilepath.setText(self.uvproj_filepath)
        self.lineeditOutputDirectory.setText(self.output_directory)

    def save_config(self):
        """保存配置"""
        settings = QSettings("config.ini", QSettings.Format.IniFormat)

        settings.setValue("uvproj_filepath", self.uvproj_filepath)
        settings.setValue("output_directory", self.output_directory)

        settings.sync()

    def show_message(self, message: str):
        """显示消息框"""
        self.textBrowserLog.append(message)

    def clear_log(self):
        """清除日志"""
        self.textBrowserLog.clear()

    def on_pushbuttonBrowseUvProj_clicked(self):
        """选择 UVPROJX 文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择 UVPROJX 文件", QDir.homePath(), "UVPROJX Files (*.uvprojx)"
        )

        if file_path == "":
            return
        
        _, ext = os.path.splitext(file_path)
        if ext != ".uvprojx":
            QMessageBox.critical(self, "错误", "请选择一个有效的 UVPROJX 文件!")
            return

        file_path = file_path.replace("/", os.sep)
        self.output_directory = os.path.dirname(file_path)
        self.uvproj_filepath = file_path

        self.lineeditUvProjFilepath.setText(self.uvproj_filepath)
        self.lineeditOutputDirectory.setText(self.output_directory)

        self.show_message(f"已选择 UVPROJX 文件: {self.uvproj_filepath}")
        self.show_message(f"输出目录修改为: {self.output_directory}，请确认是否正确。")

    def on_pushbuttonBrowseOutput_clicked(self):
        """选择输出目录"""
        dir_path = QFileDialog.getExistingDirectory(
            self, "选择输出目录", os.path.dirname(self.uvproj_filepath)
        )
        if dir_path:
            self.output_directory = dir_path.replace("/", os.sep)
            self.lineeditOutputDirectory.setText(self.output_directory)
            self.show_message(f"已选择输出目录: {self.output_directory}")

    def on_pushbuttonConvert_clicked(self):
        parser = KeilProjectToCMake(self.uvproj_filepath)

        # 解析项目文件
        if not parser.parse():
            self.show_message("解析失败!")
            return

        parser.print_project_info()

        if not parser.generate_cmake(self.output_directory):
            self.show_message("生成CMake失败!")
            return

        shutil.copytree("asset", self.output_directory, dirs_exist_ok=True)

        if (
            QMessageBox.question(
                self,
                "提示",
                "转换完成!\n是否打开输出目录?",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            )
            == QMessageBox.StandardButton.Yes
        ):
            QDesktopServices.openUrl(QUrl.fromLocalFile(self.output_directory))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = Widget()
    widget.show()
    sys.exit(app.exec())
